package com.erpanderp.wam.usm.view.user;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import com.erpanderp.wam.ac.model.entity.reimbursement.MiscExpense;
import com.erpanderp.wam.ac.model.entity.reimbursement.TravelExpense;
import com.erpanderp.wam.ac.model.entity.travel.TravelRequest;
import com.erpanderp.wam.ac.model.service.reimbursement.MiscReimbursementDAO;
import com.erpanderp.wam.ac.model.service.reimbursement.TravelReimbursementDAO;
import com.erpanderp.wam.ac.model.service.travel.TravelRequestDAO;
import com.erpanderp.wam.adm.model.entity.Module;
import com.erpanderp.wam.adm.model.entity.Note;
import com.erpanderp.wam.adm.model.service.ModuleDAO;
import com.erpanderp.wam.adm.model.service.NoteDAO;
import com.erpanderp.wam.adm.view.UserMenuBean;
import com.erpanderp.wam.asset.model.entity.AssetRequest;
import com.erpanderp.wam.asset.model.service.AssetRequestDAO;
import com.erpanderp.wam.usm.model.entity.leave.EmployeeLeave;
import com.erpanderp.wam.usm.model.entity.timesheet.Timesheet;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.leave.EmployeeLeaveDAO;
import com.erpanderp.wam.usm.model.service.timesheet.TimesheetDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.model.entity.DashboardItem;

@ManagedBean
@ViewScoped
public class WAMUserDashboardBean implements Serializable {

	HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
			.getExternalContext().getSession(true);

	private WAMUser wamUser = (WAMUser) session
			.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
	TravelRequestDAO travelRequestDAO;
	EmployeeLeaveDAO employeeLeaveDAO;
	TravelReimbursementDAO travelReimbursementDAO;
	AssetRequestDAO assetRequestDAO;
	ModuleDAO moduleDAO = new ModuleDAO();
	TimesheetDAO timesheetDAO;
	MiscReimbursementDAO miscReimbursementDAO;
	private List<DashboardItem> dashboardItems = new ArrayList<DashboardItem>();
	private List<DashboardItem> notificationItems = new ArrayList<DashboardItem>();
	private DashboardItem selectedDashboardItem;
	private TimeZone timeZone = TimeZone.getDefault();
	private boolean NOTIFICATION_FOUND;
	
	private StreamedContent file;
	
	//Get all active important notes
    private NoteDAO noteDAO=new NoteDAO();	
	private List<Note> activeNotes = new ArrayList<Note>();
	private int activeNoteSno=1;
	
	public WAMUserDashboardBean() {

		System.out.println("wamuserdashboard...");
		//Get all active notes
		activeNotes = noteDAO.getAllNotesByStatus(CommonLookup.STATUS_ACTIVE);
		for(Note note  : activeNotes){
			note.setSno(activeNoteSno);
			activeNoteSno++;
		}
		
		/*
		 * Getting all travel requests to be approved.
		 */
		if (travelRequestDAO == null)
			travelRequestDAO = new TravelRequestDAO();
		List<TravelRequest> travelRequests = travelRequestDAO.getTravelRequestsByApproverId(wamUser.getEmployee().getEmployeeId(), CommonLookup.TRAVEL_REQUEST_STATUS_INPROCESS);
		if (travelRequests != null) {
			System.out.println(travelRequests.size());
			DashboardItem dashboardItem = new DashboardItem();
			dashboardItem.setDashboardItemId(1l);
			dashboardItem.setDashboardItem("Travel Requests");
			dashboardItem.setItemCount(travelRequests.size());
			dashboardItem.setITEM_TYPE(CommonLookup.DASHBOARD_ITEM_TYPE_TRAVEL_REQUEST);
			dashboardItems.add(dashboardItem);
		}

		/*
		 * Getting all leave requests to be approved.
		 */
		if (employeeLeaveDAO == null)
			employeeLeaveDAO = new EmployeeLeaveDAO();
		List<EmployeeLeave> employeeLeaves = employeeLeaveDAO.getLeaves(wamUser.getEmployee().getEmployeeId(), CommonLookup.LEAVE_INPROCESS_STATUS);
		if (employeeLeaves != null) {
			DashboardItem dashboardItem = new DashboardItem();
			dashboardItem.setDashboardItemId(2l);
			dashboardItem.setDashboardItem("Leave Requests");
			dashboardItem.setItemCount(employeeLeaves.size());
			dashboardItem.setITEM_TYPE(CommonLookup.DASHBOARD_ITEM_TYPE_LEAVE);
			dashboardItems.add(dashboardItem);
		}
		
		
		/*
		 * Get all to be recommended Travel Claims
		 */
		if (travelReimbursementDAO == null) travelReimbursementDAO = new TravelReimbursementDAO();
		List<TravelExpense> travelExpenses = travelReimbursementDAO.getTravelExpenseRequestsByRecommenderId(wamUser.getEmployee().getEmployeeId(), "Inprocess");
		if (travelExpenses != null) {
			DashboardItem dashboardItem = new DashboardItem();
			dashboardItem.setDashboardItemId(3l);
			dashboardItem.setDashboardItem("Travel expense claims (to be recommended)");
			dashboardItem.setItemCount(travelExpenses.size());
			dashboardItem.setITEM_TYPE(CommonLookup.DASHBOARD_ITEM_TYPE_TRAVEL_EXP_CLIAM_FOR_RECOMMENDATION);
			dashboardItems.add(dashboardItem);
		}
		
		/*
		 * Get all to be approved Travel Claims
		 */
		if (travelReimbursementDAO == null) travelReimbursementDAO = new TravelReimbursementDAO();
		List<TravelExpense> travelExpensesToBeApproved = travelReimbursementDAO.getTravelExpenseRequestsByApproverId(wamUser.getEmployee().getEmployeeId(), "Inprocess");
		if (travelExpensesToBeApproved != null) {
			DashboardItem dashboardItem = new DashboardItem();
			dashboardItem.setDashboardItemId(4l);
			dashboardItem.setDashboardItem("Travel expense claims (to be approved)");
			dashboardItem.setItemCount(travelExpensesToBeApproved.size());
			dashboardItem.setITEM_TYPE(CommonLookup.DASHBOARD_ITEM_TYPE_TRAVEL_EXP_CLIAM_FOR_APPROVAL);
			dashboardItems.add(dashboardItem);
		}
		
		/*
		 * Getting all timesheets to be approved
		 */
		if (timesheetDAO == null) timesheetDAO = new TimesheetDAO();
		List<Timesheet> timesheets = timesheetDAO.getTimesheets(wamUser.getEmployee().getEmployeeId(), CommonLookup.TIMESHEET_STATUS_TO_BE_APPROVED);
		if (timesheets != null) {
			DashboardItem dashboardItem = new DashboardItem();
			dashboardItem.setDashboardItemId(5l);
			dashboardItem.setDashboardItem("Timesheets");
			dashboardItem.setItemCount(timesheets.size());
			dashboardItem.setITEM_TYPE(CommonLookup.DASHBOARD_ITEM_TYPE_TIMESHEETS);
			dashboardItems.add(dashboardItem);
		}
		
		/*
		 * Getting all misc claims
		 */
		if (miscReimbursementDAO == null) miscReimbursementDAO = new MiscReimbursementDAO();
		List<MiscExpense> miscExpenses = miscReimbursementDAO.getMiscExpenseRequestsByApproverId(wamUser.getEmployee().getEmployeeId(), CommonLookup.MISC_INPROCESS_STATUS);
		if (miscExpenses != null) {
			DashboardItem dashboardItem = new DashboardItem();
			dashboardItem.setDashboardItemId(6l);
			dashboardItem.setDashboardItem("Misc Expense Claims");
			dashboardItem.setItemCount(miscExpenses.size());
			dashboardItem.setITEM_TYPE(CommonLookup.DASHBOARD_ITEM_TYPE_MISC_EXPENSE_CLAIMS);
			dashboardItems.add(dashboardItem);
		}
		
		/*
		 * Getting all rejected Leaves
		 */
		
		Long counter = 7l;
		if (employeeLeaveDAO == null) employeeLeaveDAO = new EmployeeLeaveDAO();
		//getting both unacknowledged rejected/approved leaves
		List<EmployeeLeave> rejectedLeaves = employeeLeaveDAO.getUnacknowledgedLeaves(wamUser.getEmployee().getEmployeeId());
		
		if (rejectedLeaves != null) {
			for(EmployeeLeave employeeLeave : rejectedLeaves){
					DashboardItem dashboardItem = new DashboardItem();
					dashboardItem.setDashboardItemId(counter);
					if(employeeLeave.getApprovalStatus().equals(CommonLookup.LEAVE_REJECT_STATUS))
						dashboardItem.setDashboardItem("Leave Rejected: ");
					else
						dashboardItem.setDashboardItem("Leave Approved: ");
					dashboardItem.setEmployeeLeave(employeeLeave);
					dashboardItem.setITEM_TYPE(CommonLookup.DASHBOARD_ITEM_TYPE_LEAVE_REJECTED);
					notificationItems.add(dashboardItem);	
					counter++;	
				
			}
		}
		
		
		/*
		 * Get all to be recommended asset requests
		 */
		if (assetRequestDAO == null) 
			assetRequestDAO = new AssetRequestDAO();
		List<AssetRequest> assetRequests = assetRequestDAO.getAssetRequestsByRecommenderId(wamUser.getEmployee().getEmployeeId(), CommonLookup.STATUS_INPROCESS);
		if (assetRequests != null) {
			DashboardItem dashboardItem = new DashboardItem();
			dashboardItem.setDashboardItemId(8l);
			dashboardItem.setDashboardItem("Asset Requests (to be recommended)");
			dashboardItem.setItemCount(assetRequests.size());
			dashboardItem.setITEM_TYPE(CommonLookup.DASHBOARD_ITEM_TYPE_ASSET_REQUEST_FOR_RECOMMENDATION);
			dashboardItems.add(dashboardItem);
		}
		
		/*
		 * Get all to be recommended asset requests
		 */
		if (assetRequestDAO == null) 
			assetRequestDAO = new AssetRequestDAO(); 
		List<AssetRequest> assetRequestsToBeApproved = assetRequestDAO.getAssetRequestByApproverId(wamUser.getEmployee().getEmployeeId(), CommonLookup.STATUS_INPROCESS);
		if (assetRequestsToBeApproved != null) {
			DashboardItem dashboardItem = new DashboardItem();
			dashboardItem.setDashboardItemId(9l);
			dashboardItem.setDashboardItem("Asset Requests (to be approved)");
			dashboardItem.setItemCount(assetRequestsToBeApproved.size());
			dashboardItem.setITEM_TYPE(CommonLookup.DASHBOARD_ITEM_TYPE_ASSET_REQUEST_FOR_APPROVAL);
			dashboardItems.add(dashboardItem);
		}
		
		if(notificationItems != null && notificationItems.size() > 0){
			NOTIFICATION_FOUND = true;
		}else{
			NOTIFICATION_FOUND = false;
		}

	}

	public void downloadAction() {
		InputStream stream = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/docs/wam-user-manual.pdf");  
        file = new DefaultStreamedContent(stream, "application/pdf", "wam-user-manual.pdf");
	}

	public String showActionListener() {
		UserMenuBean userMenuBean = (UserMenuBean) session.getAttribute("userMenuBean");
		ModuleDAO moduleDAO = new ModuleDAO();
		
		//Pending leaves
		if (selectedDashboardItem.getITEM_TYPE().equals(CommonLookup.DASHBOARD_ITEM_TYPE_LEAVE)) {
			try {
				if(userMenuBean != null){
					System.out.println(userMenuBean.getSelectedModule());
					Module module = moduleDAO.getModule("Time Management");
					userMenuBean.generateMenu(module.getModuleId());
					userMenuBean.setSelectedModule(module.getModuleName());					
				}	else{
					System.out.println("NA");
				}			
				
				FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/usm/leave/viewleaves.html?redirectfrom=" + CommonLookup.PAGE_DASHBOARD);
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}

		//Pending Travel Request
		if (selectedDashboardItem.getITEM_TYPE().equals(CommonLookup.DASHBOARD_ITEM_TYPE_TRAVEL_REQUEST)) {
			try {
				if(userMenuBean != null){
				
					System.out.println(userMenuBean.getSelectedModule());
					Module module = moduleDAO.getModule("Travel Management");
					userMenuBean.generateMenu(module.getModuleId());
					userMenuBean.setSelectedModule(module.getModuleName());					
				}	else{
					System.out.println("NA");
				}
				
				FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/ac/travel/travelrequests.html?redirectfrom=" + CommonLookup.PAGE_DASHBOARD);
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		
		//Recomendation Pending Travel Claims
		if (selectedDashboardItem.getITEM_TYPE().equals(CommonLookup.DASHBOARD_ITEM_TYPE_TRAVEL_EXP_CLIAM_FOR_RECOMMENDATION)) {
			try {
				if(userMenuBean != null){				
					System.out.println(userMenuBean.getSelectedModule());
					Module module = moduleDAO.getModule("Claims");
					userMenuBean.generateMenu(module.getModuleId());
					userMenuBean.setSelectedModule(module.getModuleName());					
				}	else{
					System.out.println("NA");
				}
				
				FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/ac/reimbursement/inprocesstravelexpenses.html?redirectfrom=" + CommonLookup.PAGE_DASHBOARD);
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		
		if (selectedDashboardItem.getITEM_TYPE().equals(CommonLookup.DASHBOARD_ITEM_TYPE_TRAVEL_EXP_CLIAM_FOR_APPROVAL)) {
			try {
				if(userMenuBean != null){				
					System.out.println(userMenuBean.getSelectedModule());
					Module module = moduleDAO.getModule("Claims");
					userMenuBean.generateMenu(module.getModuleId());
					userMenuBean.setSelectedModule(module.getModuleName());					
				}	else{
					System.out.println("NA");
				}
				
				FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/ac/reimbursement/approverinprocesstravelexpenses.html?redirectfrom=" + CommonLookup.PAGE_DASHBOARD);
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		
		//Pending Timesheets
		if (selectedDashboardItem.getITEM_TYPE().equals(CommonLookup.DASHBOARD_ITEM_TYPE_TIMESHEETS)) {
			try {
				if(userMenuBean != null){				
					System.out.println(userMenuBean.getSelectedModule());
					Module module = moduleDAO.getModule("Time Management");
					userMenuBean.generateMenu(module.getModuleId());
					userMenuBean.setSelectedModule(module.getModuleName());					
				}	else{
					System.out.println("NA");
				}
				
				FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/usm/timesheet/viewtimesheets.html?redirectfrom=" + CommonLookup.PAGE_DASHBOARD);
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		
		//Pending Misc Expense Claims
		if (selectedDashboardItem.getITEM_TYPE().equals(CommonLookup.DASHBOARD_ITEM_TYPE_MISC_EXPENSE_CLAIMS)) {
			try {
				if(userMenuBean != null){				
					System.out.println(userMenuBean.getSelectedModule());
					Module module = moduleDAO.getModule("Claims");
					userMenuBean.generateMenu(module.getModuleId());
					userMenuBean.setSelectedModule(module.getModuleName());					
				}	else{
					System.out.println("NA");
				}
				
				FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/ac/reimbursement/inprocessmiscllaneousexpenses.html?redirectfrom=" + CommonLookup.PAGE_DASHBOARD);
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		
		//pending asset request for recommender	
		if (selectedDashboardItem.getITEM_TYPE().equals(CommonLookup.DASHBOARD_ITEM_TYPE_ASSET_REQUEST_FOR_RECOMMENDATION)) {
		 try {
					if(userMenuBean != null){				
						System.out.println(userMenuBean.getSelectedModule());
						Module module = moduleDAO.getModule("Asset Management");
						userMenuBean.generateMenu(module.getModuleId());
						userMenuBean.setSelectedModule(module.getModuleName());					
					}	else{
						System.out.println("NA");
					}
					
					FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/asset/recommenderinprocessassets.html?redirectfrom=" + CommonLookup.PAGE_DASHBOARD);
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		
		//pending asset request for approver	
		if (selectedDashboardItem.getITEM_TYPE().equals(CommonLookup.DASHBOARD_ITEM_TYPE_ASSET_REQUEST_FOR_APPROVAL)) {
		 try {
					if(userMenuBean != null){				
						System.out.println(userMenuBean.getSelectedModule());
						Module module = moduleDAO.getModule("Asset Management");
						userMenuBean.generateMenu(module.getModuleId());
						userMenuBean.setSelectedModule(module.getModuleName());					
					}	else{
						System.out.println("NA");
					}
					
					FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/asset/approverinprocessassets.html?redirectfrom=" + CommonLookup.PAGE_DASHBOARD);
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
			
		
		
		return null;
	}
	
	

	public String deleteDashboardItemActionListener(){
		//Rejected Leaves
		if (selectedDashboardItem.getITEM_TYPE().equals(CommonLookup.DASHBOARD_ITEM_TYPE_LEAVE_REJECTED)) {
			EmployeeLeave employeeLeave = selectedDashboardItem.getEmployeeLeave();
			employeeLeave.setManagerActionAcknowledged(CommonLookup.LEAVE_REQUEST_MANAGER_ACTION_ACKNOWLEDGED);
			employeeLeaveDAO.leaveApprovedByApprovalComments(employeeLeave);
			notificationItems.remove(selectedDashboardItem);
		}
		
		if(notificationItems != null && notificationItems.size() > 0){
			NOTIFICATION_FOUND = true;
		}else{
			NOTIFICATION_FOUND = false;
		}
		return null;
	}
	
	public List<DashboardItem> getDashboardItems() {
		return dashboardItems;
	}

	public void setDashboardItems(List<DashboardItem> dashboardItems) {
		this.dashboardItems = dashboardItems;
	}

	public WAMUser getWamUser() {
		return wamUser;
	}

	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}

	public DashboardItem getSelectedDashboardItem() {
		return selectedDashboardItem;
	}

	public void setSelectedDashboardItem(DashboardItem selectedDashboardItem) {
		this.selectedDashboardItem = selectedDashboardItem;
	}

	public List<DashboardItem> getNotificationItems() {
		return notificationItems;
	}

	public void setNotificationItems(List<DashboardItem> notificationItems) {
		this.notificationItems = notificationItems;
	}

	public boolean isNOTIFICATION_FOUND() {
		return NOTIFICATION_FOUND;
	}

	public void setNOTIFICATION_FOUND(boolean nOTIFICATION_FOUND) {
		NOTIFICATION_FOUND = nOTIFICATION_FOUND;
	}

	public StreamedContent getFile() {
		return file;
	}

	public TimeZone getTimeZone() {
		return timeZone;
	}

	public void setTimeZone(TimeZone timeZone) {
		this.timeZone = timeZone;
	}

	public NoteDAO getNoteDAO() {
		return noteDAO;
	}

	public void setNoteDAO(NoteDAO noteDAO) {
		this.noteDAO = noteDAO;
	}

	public List<Note> getActiveNotes() {
		return activeNotes;
	}

	public void setActiveNotes(List<Note> activeNotes) {
		this.activeNotes = activeNotes;
	}

	public int getActiveNoteSno() {
		return activeNoteSno;
	}

	public void setActiveNoteSno(int activeNoteSno) {
		this.activeNoteSno = activeNoteSno;
	}


}
